package com.cedifie.lendapp.ui.steps.adapter

import android.graphics.Color
import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.recyclerview.widget.RecyclerView
import com.cedifie.lendapp.R
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lendapp.weight.CedInputText
import com.cedifie.lib_baseadapter.CEDRecyclerViewAdapter
import com.cedifie.lib_baseadapter.CEDViewHolderHelper
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/18 14:46
 * @Annotation：流程常规通用适配器
 */
class CedStepCommonAdapter(recyclerView: RecyclerView?) : CEDRecyclerViewAdapter<JSONObject>(recyclerView) {

    //是否是通用样式，通用样式 tvTitle为加粗字体，非通用样式为默认字体
    var typeFaceStyle = Typeface.BOLD

    override fun getItemViewType(position: Int): Int {
        val model = getItem(position)
        return when(model.optString("action")){
            "DATE_PICK" ->{//时间选择
                R.layout.item_step_common_select
            }
            "SELECT" -> {//选择
                R.layout.item_step_common_select
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                R.layout.item_step_contact_relation
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                R.layout.item_step_common_mobile
            }
            else -> {//输入框
                R.layout.item_step_common_input
            }
        }
    }

    override fun setItemChildListener(helper: CEDViewHolderHelper, viewType: Int) {
        helper.setItemChildClickListener(R.id.selectLayout)//选择
        helper.setItemChildClickListener(R.id.textContactMobile)//选择联系人电话
        helper.setItemChildClickListener(R.id.imgContact)//选择联系人电话
    }

    override fun fillData(helper: CEDViewHolderHelper, position: Int, model: JSONObject) {
        //名称
        val tvTitle = helper.getTextView(R.id.tvTitle)
        tvTitle.text = findKeywordColor(Color.parseColor("#FFFF4D3E"),model.optString("title"),"*")
        tvTitle.setTypeface(Typeface.DEFAULT,typeFaceStyle)

        when(model.optString("action")){
            "DATE_PICK",
            "SELECT" ->{//时间选择、选择
                showSelectView(helper,position,model)
            }
            "CONTACT_GROUP_PHONE" -> {//联系人电话
                showContactMobileView(helper,position,model)
            }
            "CONTACT_GROUP_RELATION" -> {//联系人关系
                showContactRelationView(helper,position,model)
            }
            else -> {//输入框
                showInputView(helper,position,model)
            }
        }
    }

    /**
     * 输入框类型
     */
    private fun showInputView(helper: CEDViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val editText = helper.getView<CedInputText>(R.id.editText)
        editText.setHint(hint)
        var showText = ""
        if (model.has("selectItem")){
            showText = model.optJSONObject("selectItem").optString("title")
        }
        editText.setText(showText)
        editText.setInputFocusChangeListener(object : CedInputText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(CedEventType.FORM.CED_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(CedEventType.FORM.CED_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addCedEventAction(eventType,remark)
            }
        })

        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }

        editText.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })
    }

    /**
     * 选择类型
     */
    private fun showSelectView(helper: CEDViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val hint = model.optString("hint")
        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.setHint(hint)
        if (model.has("selectItem")){
            tvValue.text = model.getJSONObject("selectItem").optString("title")
        }
    }

    /**
     * 联系人关系
     */
    private fun showContactRelationView(helper: CEDViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        var hint = model.optString("hint")
        //选择关系
        val tvValue = helper.getTextView(R.id.tvValue)
        tvValue.setHint(hint)
        //输入关系
        val editText = helper.getView<CedInputText>(R.id.editText)
        //todo 此处确实选择Other时输入框的提示
        editText.setHint(model.optString("relationOtherHint"))
        editText.visibility = View.GONE

        var showTitle = ""
        var showOtherValue = ""
        if (model.has("selectItem")){
            val selectItem = model.getJSONObject("selectItem")
            showTitle = selectItem.optString("title")
            if (showTitle == model.optString("relationOtherKey")){
                editText.visibility = View.VISIBLE
                if (selectItem.has("otherValue")){
                    showOtherValue = selectItem.optString("otherValue","")
                }
            }
        }
        tvValue.text = showTitle

        //关系为“Other”时，输入框允许输入
        editText.isEnabled = showTitle == model.optString("relationOtherKey")
        editText.setText(showOtherValue)
        editText.setInputFocusChangeListener(object : CedInputText.IInputFocusChangeListener{
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(CedEventType.FORM.CED_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(CedEventType.FORM.CED_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addCedEventAction(eventType,remark)
            }
        })
        editText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editText.clearFocus()
                true
            }
            false
        }

        editText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                if (model.has("selectItem")){
                    val selectItem = model.getJSONObject("selectItem")
                    selectItem.put("otherValue",s.toString())
                }
            }
        })
    }

    /**
     * 联系人电话
     */
    private fun showContactMobileView(helper: CEDViewHolderHelper, position: Int, model: JSONObject){
        //提示语
        val showHint = model.optString("hint")
        val tvValue = helper.getTextView(R.id.textContactMobile)
        tvValue.setHint(showHint)
        val editMobile = helper.getView<CedInputText>(R.id.editContactMobile)
        editMobile.setHint(showHint)
        if (model.has("selectItem")){
            val showValue = model.getJSONObject("selectItem").optString("title")
            tvValue.text = showValue
            editMobile.setText(showValue)
        }
        editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE){
                editMobile.clearFocus()
                true
            }
            false
        }
        editMobile.setInputFocusChangeListener(object : CedInputText.IInputFocusChangeListener {
            override fun onFocusChange(v: View?, hasFocus: Boolean) {
            }
            override fun onCompleteAction(v: View?, remark: String) {
                var eventType = String.format(CedEventType.FORM.CED_FORM_STEP_INPUT_XX,model.optString("paramName"))
                if (model.has("stepType") && model.optString("stepType") == "CONTACT"){
                    eventType = String.format(CedEventType.FORM.CED_FORM_STEP_INPUT_XX,"${model.optString("stepTitle")}_${model.optString("paramName")}_${model.optString("stepItemIndex")}")
                }
                HttpHelper.addCedEventAction(eventType,remark)
            }
        })
        editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                val obj = JSONObject()
                obj.put("title",s.toString())
                obj.put("value",s.toString())
                model.put("selectItem",obj)
            }
        })

        //是否是审核账号
        val isConfigAccount = SharedHelper.getCedSPBoolean(SharedHelper.CED_SPKEY.CEDIFIE_IS_AUDIT)
        if(isConfigAccount){//审核账号 - 允许输入或选择
            tvValue.visibility = View.GONE
            editMobile.visibility = View.VISIBLE
        } else {//非审核账号只能选择
            //设备是否支持通讯录选择联系人
            if (model.optBoolean("isContactPick")){
                tvValue.visibility = View.VISIBLE
                editMobile.visibility = View.GONE
            } else {
                tvValue.visibility = View.GONE
                editMobile.visibility = View.VISIBLE
            }
        }
    }

    private fun findKeywordColor(color: Int, text: String, key: String): SpannableString {
        val spString = SpannableString(text)
        if (!text.contains(key)){
            return spString
        }
        val start = text.indexOf(key)
        val end = start + key.length
        spString.setSpan(ForegroundColorSpan(color), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spString
    }
}